package com.example.votesystem.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.votesystem.entity.UFile;
import com.example.votesystem.entity.UploadFile;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 图片上传工具类
 */
public class FileUploadUtil {

    static String ROOT = "http://localhost:8080/";

    @RequestMapping(value = "/uploadFile", produces = "text/plain; charset=utf-8")
    public static String uploadFile(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) throws UnsupportedEncodingException {
        UploadFile upFile = new UploadFile();
        String path = request.getSession().getServletContext().getRealPath("/upload/");
        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 新文件名
        fileName = UUID.randomUUID() + suffixName;
//        String fileNameEncode = encode(fileName,"UTF-8");

        if (file.getSize() > 1024 * 1024 * 10) {
            upFile.setCode(1);
            upFile.setMsg("单个文件/图片大小不能超过10M!");
            return JSON.toJSONString(upFile);
        }
        File targetFile = new File(path, fileName);

        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);
            upFile.setCode(0);
            UFile uf = new UFile();
            uf.setName(fileName);
            uf.setSrc(ROOT + "/sns/downLoadFile?fileName=" + fileName);
            upFile.setData(uf);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(upFile);
    }
}